﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CommonLib;

namespace ModbusProject
{
    public partial class ReadTemperature2 : Form
    {
        string portName = "COM3";
        //int baudRate = 9600;
        //Parity parity = Parity.None;
        //StopBits stopBits = StopBits.One;
        //int dataBits = 8;

        private bool isReading = false; // 控制读取循环的标志
        private Thread readThread;      // 后台读取线程
        private ModbusRTU modbus;       // 单例 ModbusRTU 实例
        private readonly object lockObject = new object(); // 锁对象
        public ReadTemperature2()
        {
            InitializeComponent();
            modbus = new ModbusRTU(portName);
            string errorMsg;
            if(modbus.Connect(out errorMsg))
            {
                MessageBox.Show("连接成功！");
            }
            else
            {
                MessageBox.Show($"连接到 Modbus 设备失败: {errorMsg}");
            }
        }

        public ushort GetTemperatureValue()
        {
            lock(lockObject)
            {
                string errorMsg;
                ushort temperatureValue;

                byte slaveId = 0x01; // 设备地址
                ushort registerAddress = 0x0400; // 寄存器地址
                ushort registerNums = 0x0001; // 读取一个寄存器
                byte functionCode = 0x04; // 功能码
                // 读取寄存器数据
                bool result;
                byte[] dataArray = modbus.ReadRegisters(slaveId, registerAddress, registerNums, functionCode, out result, out errorMsg);
                if (result)
                {
                    // 将字节数组转换为 ushort 数组
                    ushort[] values = modbus.ConvertByteArrayToShortArray(dataArray);

                    temperatureValue = (ushort)(values[0] / 10);
                    return temperatureValue;
                }
                else
                {
                    MessageBox.Show($"读取温度数据失败: {errorMsg}");
                }
            }
           
            // 默认返回值，表示读取失败
            return 0;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (!isReading)
            {
                isReading = true;
                btnConnect.Text = "停止读取";

                // 创建并启动后台线程
                readThread = new Thread(ReadTemperatureLoop);
                readThread.IsBackground = true;
                readThread.Start();
            }
            else
            {
                isReading = false;
                btnConnect.Text = "开始读取";

                // 等待线程结束
                if (readThread != null && readThread.IsAlive)
                    readThread.Join();

                string errorMsg;
                modbus.DisConnect(out errorMsg);
            }
        }

        private void AutoReadTemperature()
        {
            while (isReading)
            {
                ushort temperature = GetTemperatureValue();
               
                    this.Invoke((MethodInvoker)delegate
                    {
                        lblTemperature.Text = $"当前温度: {temperature} °C";
                    });
                
                Thread.Sleep(1000);
            }

        }
        private void ReadTemperatureLoop()
        {
            while (isReading)
            {
                ushort temperature = GetTemperatureValue();

                // 使用 Invoke 安全更新 UI
                this.Invoke((MethodInvoker)delegate
                {
                    if (temperature != 0)
                        lblTemperature.Text = $"当前温度: {temperature} °C";
                    else
                        lblTemperature.Text = "温度读取失败";
                });

                Thread.Sleep(1000); // 每秒读取一次
            }
        }
    }
}
